# encoding: utf-8
class Admin::AppConnectionsController < AdminController

  set_tab :statistics
  set_tab :connections, :sub_nav
  before_filter :setup, only: [:index]
  
  def index
    @app_connections = AppConnection.includes(:app).order('created_at desc')
    respond_to do |format|
      format.html {
        @app_connections = @app_connections.page params[:page]
      }
      format.csv {   
        send_data(csv_content_for(@app_connections),  
                  :type => "text/csv;charset=utf-8; header=present",  
                  :filename => "连接统计_#{Time.now.strftime("%Y%m%d")}.csv")  
      }
    end
  end

  private

  def setup
    @ways = ["统计","连接统计"]
    @left_panel = "layouts/statistics_left_panel"
  end

  def csv_content_for(objs)  
    CSV.generate do |csv|  
      csv << ["\xEF\xBB\xBFAPP", "时长", "时间"]  
      objs.each do |connection|  
        csv << [  
          connection.app.mac,  
          connection.duration,
          connection.created_at.stamp("2013-03-12 22:01:01")
        ]
      end
    end
  end
end
